# -*- coding: utf-8 -*-

from flask import render_template, request, session, url_for, redirect, Blueprint

from app import db
from .forms import ArticleCreateForm, ArticleUpdateForm
from app.person.models import Person
from .models import Article
from app.utils import HTTPNotFound


mod = Blueprint('article', __name__)

@mod.route('/')
def index():
    articles = Article.all()
    return render_template('article/index.html', articles=articles)

@mod.route('/profile/', methods=['GET', 'POST'])
def profile():
    if 'email' not in session:
        return redirect(url_for('person.signin'))
    person = Person.query.filter_by(email=session['email']).first()
    if person:
        article = Article()
        form = ArticleCreateForm()
        if request.method == 'POST' and form.validate_on_submit():
            form.populate_obj(article)
            db.session.add(article)
            db.session.commit()
            return redirect(url_for('article.index'))
        else:
            return render_template('article/create.html', form=form)
    return render_template('article/profile.html')


@mod.route('/article/<int:id>/<slug>')
def show_article(id, slug):
    article = Article.find_by_id(id)
    return render_template('article/show_article.html', article=article)

@mod.route('/article/<int:id>/<slug>/edit', methods=['GET', 'POST'])
def article_update(id, slug):
    article = Article.find_by_id(id)
    if not article:
        return HTTPNotFound(404)
    form = ArticleUpdateForm(request.form, article)
    if form.validate_on_submit():
        form.populate_obj(article)
        db.session.add(article)
        db.session.commit()
        return redirect(url_for('article.index'))
    return render_template('article/create.html', form=form, update=True)
